import json
from channels.exceptions import StopConsumer
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from asgiref.sync import async_to_sync
import uuid

message_list = []
user_list = {

}
ip = ''


# 群聊的用户名要一致
# 字典转json
def to_json(dic):
    return json.dumps(dic)


# json转字典
def to_obj(json_str):
    return json.loads(json_str)


# 同步方式，仅作示例，不使用
class SyncConsumer(WebsocketConsumer):
    def connect(self):

        self.room_name = 'chatRoom'
        self.room_group_name = 'web'
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name, self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name, self.channel_name
        )

    # 从WebSocket中接收消息
    def receive(self, text_data=None, bytes_data=None):
        """
        code : 106,进入房间，
        code : 108,发送消息，
        code : 110,离开房间，
        """
        global ip
        ip = f"{self.scope['client'][0]}-{self.scope['client'][1]}"
        print(ip)
        data = to_obj(text_data)
        event = {
            'type': 'chat_message',
            'message': data
        }
        async_to_sync(self.channel_layer.group_send)(self.room_group_name, event)

    def chat_message(self, event):
        data = event['message']
        code = data['code']
        fun_dic = {
            106: self.enter_room,
            108: self.to_msg,
            110: self.leave_room,
        }
        fun = fun_dic.get(code)
        data['number_people'] = len(user_list)
        fun(data)

    # 进入房间
    def enter_room(self, data):
        data['msg'] = f"{ip} 进入房间"
        user_list[data['uuid']] = data['uuid']
        data['number_people'] = len(user_list)
        self.send(to_json(data))
        return

    # 收发消息
    def to_msg(self, data):
        self.send(to_json(data))
        return

    # 离开房间
    def leave_room(self, data):
        data['msg'] = f"{ip} 离开房间"
        if user_list.get(data['uuid']):
            del user_list[data['uuid']]

        data['number_people'] = len(user_list)
        self.send(to_json(data))
        return
